const nodemailer = require('nodemailer');
const crypto = require('crypto');

// 邮箱相关的配置
const smtp = {
    host: 'smtp.exmail.qq.com',
    port: 465, // true for 465, false for other ports
    secureConnection: true,
    service: 'qq',
    auth: {
        user: '3258379404@qq.com', // 发送邮件的邮箱名
        pass: 'nabrnoahrxixcgja', // 邮箱的授权码，也可以使用邮箱登陆密码 
        // user: '3292868076@qq.com', // 发送邮件的邮箱名
        // pass: 'qomnnfrsugafdcai', // 邮箱的授权码，也可以使用邮箱登陆密码
    },
};

module.exports = {
    //验证邮箱
    testEmail(email) {
        const reg = /^[A-Za-z0-9]+([_\.][A-Za-z0-9]+)*@([A-Za-z0-9\-]+\.)+[A-Za-z]{2,6}$/;
        return reg.test(email);
    },
    //发送邮箱验证码
    async sendEmail(obj) {
        console.log(obj);
        //创建一个SMTP客户端配置
        const transporter = nodemailer.createTransport(smtp);
        try {
            const info = await transporter.sendMail(obj);
            console.log(info);
            return {
                code: 1,
                msg: "发送成功"
            }
        } catch (err) {
            console.log(err);
            return {
                code: 0,
                msg: "发送失败"
            }
        }


    },
    //生成随机数
    rand(length = 6) {
        let str = "";
        for (let i = 0; i < length; i++) {
            str += Math.floor(Math.random() * 10);
        }
        return str;
    },
    //加密
    genSign(text) {
        const key = Buffer.from(this.app.config.secret.key, 'utf8');
        const iv = Buffer.from(this.app.config.secret.iv, 'utf8');
        let sign = '';
        const cipher = crypto.createCipheriv('aes-128-cbc', key, iv);
        sign += cipher.update(text, 'utf8', 'hex');
        sign += cipher.final('hex');
        return sign;
    },
    //解密
    deSign(sign) {
        const key = Buffer.from(this.app.config.secret.key, 'utf8');
        const iv = Buffer.from(this.app.config.secret.iv, 'utf8');
        let text = '';
        const cipher = crypto.createDecipheriv('aes-128-cbc', key, iv);
        text += cipher.update(sign, 'hex', 'utf8');
        text += cipher.final('utf8');
        return text;
    },
    //生成不重复的随机数
    uniqueRandomNumber() {
        return Number(Math.random().toString().substring(2) + Date.now()).toString(36);
    }
}